package com.shanhy.lixp.need001.service;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mysema.commons.lang.URLEncoder;
import com.shanhy.lixp.need001.model.QichachaCompanyDetail;

/**
 * HTML解析
 *
 * @author 单红宇(365384722)
 * @myblog http://blog.csdn.net/catoop/
 */
@Service
public class QichachaHtmlParser {

	// private static final Logger logger =
	// LoggerFactory.getLogger(QichachaHtmlParser.class);

	// 查询URL
	private String searchUrl = "http://www.qichacha.com/search?key=";

	@Autowired
	private QichachaHtmlRequest qichachaHtmlRequest;

	/**
	 * 解析HTML
	 *
	 * @param qichachaListHtml
	 * @return
	 * @author SHANHY
	 */
	public String jsoupQichachaSearchHtml(String companyName, String html) {
		if(doVerify(html))
			return "1";// 频繁访问，被系统过滤了，需要登录网址进行验证
		
		if (!html.contains("m_srchList"))// 没有查询结果
			return "2";// 没有查询结果

		Document doc = Jsoup.parse(html);
		Element searchTable = doc.getElementsByClass("m_srchList").get(0);
		Element searchTableTbody = searchTable.getElementsByTag("tbody").get(0);
		Element firstTr = searchTableTbody.getElementsByTag("tr").get(0);
		Element companyInfoTd = firstTr.getElementsByTag("td").get(1);
		Element companyInfoLink = companyInfoTd.getElementsByTag("a").get(0);

		String name = companyInfoLink.text();
		String detailUrl = companyInfoLink.attr("href");

		if (companyName.replaceAll("[（|）|(|)]", "").equals(name.trim().replaceAll("[（|）|(|)]", "")))
			return detailUrl;

		return "3";// 获取的数据和查询的数据不完全一致
	}
	
	/**
	 * 解析HTML
	 *
	 * @param qichachaListHtml
	 * @return
	 * @author SHANHY
	 */
	public String[] jsoupQichachaDetailHtml(String companyName, String html) {
		if(doVerify(html))
			return new String[]{"1"};// 频繁访问，被系统过滤了，需要登录网址进行验证
		
		if (!html.contains(companyName))
			return new String[]{"2"};// 没有查询结果

		Document doc = Jsoup.parse(html);
		Element infoTable = doc.getElementsByClass("m_changeList").get(0);
		// 获得经营范围
		Element businessScopeTr = infoTable.getElementsContainingOwnText("经营范围：").get(0).parent();
		String businessScopeContent = businessScopeTr.getElementsByTag("td").get(1).text();
		
		// 获得企业地址
		Element addressTr = infoTable.getElementsContainingOwnText("企业地址：").get(0).parent();
		String addressContent = addressTr.getElementsByTag("td").get(1).text();
		
		if(addressContent != null)
			addressContent = addressContent.replaceAll("[查看地图|\\s]", "");

		return new String[]{businessScopeContent, addressContent};
	}

	/**
	 * 查询企业（获取查询结果的第一个）
	 * 
	 * @param name
	 * @return
	 */
	public String searchCompanyId(String name) {
		String html = qichachaHtmlRequest.getPageHtml(searchUrl.concat(URLEncoder.encodeParam(name, "UTF-8")));
		String detailUrl = jsoupQichachaSearchHtml(name, html);
		
		if (detailUrl != null) {
			if(!detailUrl.equals("1") && !detailUrl.equals("2") && !detailUrl.equals("3"))
				detailUrl = detailUrl.substring(detailUrl.indexOf("_") + 1, detailUrl.lastIndexOf("."));
		}
		return detailUrl;
	}

	/**
	 * 根据企业详情页面的URL读取企业信息
	 * 
	 * @param companyName
	 * @param companyId
	 * @return
	 */
	public QichachaCompanyDetail getDetail(String companyName, String companyId) {
		String detailUrl = "http://www.qichacha.com/company_getinfos?tab=base&unique=" + companyId + "&companyname="
				+ URLEncoder.encodeParam(companyName, "UTF-8");
		String html = qichachaHtmlRequest.getPageHtml(detailUrl);
		String[] sArr = jsoupQichachaDetailHtml(companyName, html);

		QichachaCompanyDetail detail = new QichachaCompanyDetail();
		if (sArr != null && sArr.length > 1) {
			String businessScopeContent = sArr[0];
			String addressContent = sArr[1];
			detail.setName(companyName);
			detail.setId(companyId);
			detail.setBusinessScope(businessScopeContent);
			detail.setAddress(addressContent);
		}else if(sArr != null && sArr.length == 1){
			detail.setErrorCode(sArr[0]);
		}else{
			detail = null;
		}
		return detail;
	}

	/**
	 * 验证是否需要验证
	 *
	 * @param html
	 * @return
	 * 
	 * @author 单红宇(CSDN CATOOP)
	 * @create 2017年5月3日
	 */
	public boolean doVerify(String html){
		return html.contains("/index_verify");
	}

}
